package com.yanfan.energybilling.service.impl;

import com.yanfan.common.core.redis.RedisCache;
import com.yanfan.energybilling.domain.TDEnergyDeductionRecord;
import com.yanfan.energybilling.domain.dto.TDEnergyDeductionRecordDto;
import com.yanfan.energybilling.service.IRecordImportService;
import com.yanfan.energybilling.service.ITDEnergyDeductionRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class RecordImportServiceImpl implements IRecordImportService {

    @Autowired
    private ITDEnergyDeductionRecordService itdEnergyDeductionRecordService;
    @Autowired
    private RedisCache redisCache;

    @Transactional
    @Override
    public String recordImport(List<TDEnergyDeductionRecord> recordList) {
        recordList.stream().collect(Collectors.groupingBy(TDEnergyDeductionRecord::getDeviceNumber)).forEach((serialNumber, records) -> {
            TDEnergyDeductionRecordDto recordDto = new TDEnergyDeductionRecordDto();
            recordDto.setSerialNumber(serialNumber);
            for (TDEnergyDeductionRecord record : records) {
                record.setTsLong(getNewTime(record.getTs()));
            }
            recordDto.setList(records);
            itdEnergyDeductionRecordService.insertBatchRecord(recordDto);
        });
        return "导入成功";
    }

    private Long getNewTime(Date date) {
        long time = date.getTime();
        String key = "record_time";
        String hKey = date.getTime() + "";

        Long dateTime = redisCache.getCacheMapValue(key, hKey);
        if (Objects.isNull(dateTime)) {
            long begin = time * 1000L * 1000L;
            long end = (time + 1L) * 1000L * 1000L;
            dateTime = itdEnergyDeductionRecordService.selectTimeRangeLast(begin, end);
            if (Objects.isNull(dateTime)) {
                dateTime = begin;
            } else {
                dateTime = dateTime + 1L;
            }

        } else {
            dateTime = dateTime + 1L;
        }
        redisCache.setCacheMapValue(key, hKey, dateTime);
        redisCache.expire(key, 10, TimeUnit.MINUTES);
        return dateTime;

    }
}
